#include <fstream>
#include <cstdlib>
#include <cstring>
#include "headfiles.h"

using namespace std;

int main(int argc, char **argv) {
    if (argc != 2) {
        cout << "Usage: " << argv[0] << " in_file" << endl;
        return 0;
    }

    string file_name(argv[1]);
    fstream fs;
    fs.open(file_name.c_str(), fstream::in);
    if (!fs.is_open()) {
        cout << "File " << file_name << " open error!" << endl;
        return 1;
    }

    string str;
    char **str_array;
    fs >> str;
    int str_num = atoi(str.c_str());
    str_array = (char **)malloc(sizeof(char *) * str_num);
    if (str_array == NULL) {
        cout << "Allocate string array error, NULL!" << endl;
        return 1;
    }

    int loc = 0;
    while (fs >> str) {
        if (str.empty()) {
            break;
        }

        size_t str_size = str.size();

        str_array[loc] = (char *)malloc(sizeof(char) * (str_size + 1));
        memcpy(str_array[loc], str.c_str(), str_size);
        str_array[loc][str_size] = '\0';
        loc++;
    }
    fs.close();

    int i;
    for (i = 0; i < str_num; i++) {
        cout << "String " << i << ": ";
        cout << str_array[i] << endl;
    }
    cout << endl;

    sortStrings(str_array, str_num);

    for (i = 0; i < str_num; i++) {
        cout << "String " << i << ": ";
        cout << str_array[i] << endl;
    }
    cout << endl;

    for (i = 0; i < str_num; i++) {
        free(str_array[i]);
    }
    free(str_array);

    return 0;
}

